package com.corgi.encrypt.advice;

import com.corgi.encrypt.annotation.Decrypt;
import com.corgi.encrypt.properties.EncryptProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @title: EncryptRequestBodyAdvice
 * @description:
 * @author: dengmiao
 * @create: 2019-10-23 15:20
 **/
@Slf4j
@ControllerAdvice
public class EncryptRequestBodyAdvice implements RequestBodyAdvice {

    private boolean encrypt;

    @Autowired
    private EncryptProperties encryptProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (methodParameter.getMethod().isAnnotationPresent(Decrypt.class) && encryptProperties.isOpen()) {
            encrypt = true;
        }
        return encrypt;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        if (encrypt) {
            try {
                return new DecryptHttpInputMessage(httpInputMessage, encryptProperties.getPrivateKey(), encryptProperties.getCharset(), encryptProperties.isShowLog());
            } catch (Exception e) {
                log.error("Decryption failed", e);
            }
        }
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
